<template>
  <div style="background-color: #f0f2f5; padding: 0px;">
    <PageHeader
      :breadcrumb="breadcrumb"
      style="background-color: white; padding: 24px; margin-bottom: 16px;"
    />
    <div style="background-color: white; padding: 24px; padding-top: 0px;">
      <div id="operationButton">
        <a-button
          v-if="canAddUser"
          size="large"
          type="primary"
          @click="onAddButtonClick"
        >
          添加
        </a-button>
        <a-modal
          v-model:visible="addOrEditDialogVisible"
          :title="addOrEditDialogTitle"
          :width="800"
          :keyboard="false"
          :maskClosable="false"
          :footer="null"
          :destroyOnClose="true"
          centered
        >
          <AddOrEditUser
            :url="editUrl"
            @operate-success="onAddOrEditSuccess"
            @operate-failed="closeAddOrEditDialog"
          />
        </a-modal>
      </div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="{ pageSize: 10 }"
        :scroll="{ x: 240 }"
      >
        <template v-if="canEditUser || canDeleteUser" #operation="{ record }">
          <TableOperation
            :canEdit="canEditUser"
            :canDelete="canDeleteUser"
            @edit="onEdit(record.key)"
            @delete="onDelete(record.key)"
          />
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import PageHeader from '../Common/PageHeader'
import AddOrEditUser from './AddOrEditUser'
import TableOperation from '../Common/TableOperation'
import { message } from 'ant-design-vue'

const operationColumn = {
  title: '操作',
  dataIndex: 'operation',
  slots: { customRender: 'operation' },
  width: 100,
}

export default {
  name: 'UserInfo',
  emits: ['add'],
  components: {
    PageHeader,
    AddOrEditUser,
    TableOperation,
  },
  data() {
    const refreshInterval = 100
    return {
      breadcrumb: [
        { key: 1, title: '用户管理' },
        { key: 2, title: '用户信息' },
      ],
      data: [],
      loading: false,
      addOrEditDialogVisible: false,
      addOrEditDialogTitle: '',
      canAddUser: false,
      canEditUser: false,
      canDeleteUser: false,
      editUrl: '',
      columns: [],
      refreshInterval,
    }
  },
  mounted() {
    this.columns = this.getDataColumns()
    this.processPermission()
    this.fetch()
  },
  methods: {
    getDataColumns() {
      return [
        {
          title: '用户名',
          dataIndex: 'username',
          width: 250,
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 250,
        },
      ]
    },
    // 处理权限
    processPermission() {
      this.axios
        .get('/has_permission?permission=user_management.add_user')
        .then((res) => {
          this.canAddUser = res.data.result
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get('/has_permission?permission=user_management.change_user')
        .then((res) => {
          this.canEditUser = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canEditUser
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
      this.axios
        .get('/has_permission?permission=user_management.delete_user')
        .then((res) => {
          this.canDeleteUser = res.data.result
          let last = this.columns.length
          if (
            this.columns[last - 1].dataIndex !== 'operation' &&
            this.canDeleteUser
          ) {
            this.columns.push(operationColumn)
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
        })
    },
    // 从后端获取数据
    fetch() {
      this.loading = true
      let updatedData = []
      this.axios
        .get('/user_management/users/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            updatedData.push({
              key: data[i].url,
              username: data[i].username,
              gender: data[i].readable_gender,
            })
          }
          setTimeout(() => {
            this.data = updatedData
            this.loading = false
          }, this.refreshInterval)
          //   console.log(res)
        })
        .catch((error) => {
          setTimeout(() => {
            this.loading = false
          }, this.refreshInterval)
          console.log('Error', error.message)
        })
    },
    onAddButtonClick() {
      this.addOrEditDialogTitle = '添加用户'
      this.editUrl = ''
      this.addOrEditDialogVisible = true
      // this.$emit('add')
    },
    onAddOrEditSuccess() {
      this.closeAddOrEditDialog()
      this.fetch()
    },
    closeAddOrEditDialog() {
      this.addOrEditDialogVisible = false
    },
    onEdit(key) {
      this.addOrEditDialogTitle = '编辑用户'
      // console.log(key)
      this.editUrl = key
      this.addOrEditDialogVisible = true
    },
    onDelete(key) {
      message.loading({ content: '删除中...', key })
      const data = [...this.data]
      this.axios
        .delete(key)
        .then(() => {
          setTimeout(() => {
            message.success({ content: '删除成功！', key, duration: 2 })
            this.data = data.filter((item) => item.key !== key)
          }, 1000)
        })
        .catch((error) => {
          setTimeout(() => {
            message.error({ content: '删除失败！', key, duration: 2 })
          }, 1000)
          console.log('Error', error.message)
        })
    },
  },
}
</script>

<style>
#operationButton {
  text-align: right;
}
</style>
